﻿/*
* Sunbox DataView
* Tool for customizing layout in SharePoint
*
* Examples and documentation at: http://sunbox.codeplex.com
* 
* Copyright (c) 2011 - 2012 SKB KONTUR
* Many people have submitted bugs, code, and offered their advice freely. Their support is greatly appreciated.
* 
* Version: 1.0.1 (20/01/2012)
* Requires: jQuery v1.3+, Fancybox 1.3.4, CodeMirror
*
* LGPL license:
*   http://www.gnu.org/licenses/lgpl.html
*/

$.fn.extend({
    xslsourceeditorpart: function (options) {
        var a_obj = [];
        $(this).each(function () {
            if (!$(this).hasClass("xve-done")) {
                a_obj.push(new XslSourceEditorPart(this, options));
                $(this).addClass("xve-done");
            }
        });
        if (a_obj.length == 1)
            return a_obj[0];
        return a_obj;
    }
});

XslSourceEditorPart = (function () {

    function XslSourceEditorPart(container, options) {
        this.options = $.extend({}, this.defaults(), options);
        this.jqContainer = $(container);
        this.init();
    }

    XslSourceEditorPart.prototype.init = function () {
        var $this = this;
        this.jqHidden = $("#" + this.options.controlid);
        if (this.jqHidden.val().length > 0)
            this.xslSource = JSON.parse(this.jqHidden.val());
        else
            this.xslSource = { Title: "", Xsl: "" };

        if (this.jqHidden.length < 0)
            return;

        //init lang
        if (typeof SunboxDataView.lang[this.options.lang] != 'undefined')
            this.locale = SunboxDataView.lang[this.options.lang];
        else
            this.locale = SunboxDataView.lang.en;

        var wrap = $("<div />").addClass("xs-wrap");

        this.jqContainer.append(wrap);
        this.jqContainer.append("<div style='display:none;'>" + this.buildXslSourceForm(this.xslSource) + "</div>");
        $(".xs-form-title").val(this.xslSource.Title);
        window.__sunboxxsleditor.setValue(this.xslSource.Xsl);

        this.refreshXslSourceList();

        $(".xs-form-submit").click(function () {
            if (!$this.validateForm(this))
                return;
            var opt = $this.getCurrentFormValues(this);
            $this.xslSource.Title = opt.titleInput.val();
            $this.xslSource.Xsl = window.__sunboxxsleditor.getValue();
            $this.saveXslSources();
            $this.refreshXslSourceList();
            $.fancybox.close();
        });

        $(".xs-form-cancel").click(function () {
            $.fancybox.close();
        });

        $("#ds-form-generatexsl").click(function () {
            if (!confirm($this.locale.xslEditorGenerateXslQuestion)) return;
            var dsEditorPart = window.__xsldatasourceseditorpart;
            if (typeof dsEditorPart == "undefined") return;

            var xsl = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n";
            xsl += "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\r\n";
            xsl += "\t<xsl:template match=\"/\">\r\n";
            for (var i = 0; i < dsEditorPart.datasources.length; i++) {
                xsl += "\t\t<h3>" + dsEditorPart.datasources[i].Title + "</h3>\r\n";
                xsl += "\t\t<xsl:for-each select=\"/response/" + dsEditorPart.datasources[i].Title + "/Rows/Row\">\r\n";
                xsl += "\t\t\t<p>\r\n";
                xsl += "\t\t\t\t<xsl:value-of select=\"Title\" />, Modified: <xsl:value-of select=\"Modified\" />\r\n";
                xsl += "\t\t\t</p>\r\n";
                xsl += "\t\t</xsl:for-each>\r\n";
            }
            xsl += "\t</xsl:template>\r\n";
            xsl += "</xsl:stylesheet>";
            window.__sunboxxsleditor.setValue(xsl);

        });


    };

    XslSourceEditorPart.prototype.validateForm = function (obj) {
        var opt = this.getCurrentFormValues(obj);
        if (opt.titleInput.val().length == 0) {
            opt.titleInput.after(" <span class='ds-form-error ds-required'>" + this.locale.xslEditorFileNameRequiredValidationMessage + "</span>");
            return false;
        }
        opt.form.find(".ds-form-error").remove();
        return true;
    };

    XslSourceEditorPart.prototype.refreshXslSourceList = function () {
        var wrap = $(".xs-wrap");
        var html = "<div class='ds-list-wrap'>";
        html += "<div class='ds-list-item'>";
        html += (this.xslSource.Title.length > 0 ? this.xslSource.Title : this.locale.xslEditorNotConfigured) + " (<a class='xs-settings' href='#xsl-settings'>" + this.locale.xslEditorEdit + "</a>)";
        html += "</div>";
        wrap.html(html);
        var $this = this;
        $(".xs-settings").fancybox({
            onClosed: function () {

                var form = $(this.orig[0]).attr("href");
                $this.resetForm($(form).find(".xs-form-title"));

            },
            onComplete: function () {
                window.__sunboxxsleditor.refresh();
            },
            titleShow: false,
            width: 980,
            autoDimensions: false,
            height: "auto",
            autoSize: false,
            transitionIn: "none",
            transitionOut: "none",
            openSpeed: 0,
            closeSpeed: 0
        });

    };

    XslSourceEditorPart.prototype.resetForm = function (obj) {
        var opt = this.getCurrentFormValues(obj);
        opt.titleInput.val(this.xslSource.Title);
        window.__sunboxxsleditor.setValue(this.xslSource.Xsl);
        opt.form.find(".ds-form-error").remove();
    };

    XslSourceEditorPart.prototype.getCurrentFormValues = function (obj) {
        var $form = $(obj).closest(".ds-form");
        var $titleInput = $form.find(".xs-form-title");

        return { form: $form, titleInput: $titleInput };
    };

    XslSourceEditorPart.prototype.saveXslSources = function () {
        var sourcedata = JSON.stringify(this.xslSource);
        this.jqHidden.val(sourcedata);
    };

    XslSourceEditorPart.prototype.buildXslSourceForm = function () {

        var html = "<div class='ds-form' id='xsl-settings'>";
        html += "<h2>XSL шаблон</h2>";

        html += "<input type='hidden' class='ds-form-id' />";

        html += "<div class='ds-form-line'>";
        html += "   <div class='ds-form-label'>" + this.locale.xslEditorFileName + ":</div>";
        html += "   <div class='ds-form-field'><input class='xs-form-title'  value='' type='text' />.xsl <input type='button' id='ds-form-generatexsl' value='" + this.locale.xslEditorGenerateXsl + "' /></div>";
        html += "</div>";

        html += "<div class='ds-form-line sunbox-xsl-editor'>";
        html += "   <div class='ds-form-label'>" + this.locale.xslEditorXslTemplate + ":</div>";
        html += "   <div class='ds-form-field' style='font-size:16px;'><textarea rows='35' class='xs-form-xsl' cols='85' id='sunbox-xsl-editor-textarea' ></textarea></div>";
        html += "</div>";

        html += "<div class='ds-form-buttons'>";
        html += "   <input type='button' class='xs-form-submit' value='" + this.locale.xslEditorSubmit + "' />  <a class='xs-form-cancel' href='javascript:void(0);'>" + this.locale.xslEditorCancel + "</a>";
        html += "</div>";
        html += "<script>";
        html += "var __sunboxxsleditor =  CodeMirror.fromTextArea(document.getElementById('sunbox-xsl-editor-textarea'), { mode: {name: 'xml', alignCDATA: true}, lineNumbers: true });";
        html += "</script>";

        html += "</div>";

        return html;
    };

    XslSourceEditorPart.prototype.defaults = function () {
        return {
            controlid: "",
            lang: "en"
        };
    };

    return XslSourceEditorPart;
})();